package com.asiainfo.dacp.datastash.worker.executor.adapter.datax.translate.datasource;

import org.apache.commons.vfs2.FileSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.asiainfo.dacp.crypto.Crypto;
import com.asiainfo.dacp.crypto.cipher.AesCipher;
import com.asiainfo.dacp.crypto.cipher.DesCipher;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.model.Constant;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.model.PluginType;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.CommonErrorCode;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.Configuration;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.VFSUriParser;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.VFSUriParser.VFSRelInfo;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.WorkerException;
import com.asiainfo.dacp.metamodel.domain.ds.model.MetaDataSource;
import com.asiainfo.dacp.metamodel.domain.ds.repo.MetaDataSourceRepository;
import com.google.common.base.Strings;


public class DataSourceStrategyMixDBAndParam implements DataSourceStrategy {
	private static final Logger LOG = LoggerFactory.getLogger(DataSourceStrategyMixDBAndParam.class);
	@Autowired
	private MetaDataSourceRepository dsRepository;

	@Override
	public MetaDataSource getDataSource(Configuration conf) {

		String stepInst = conf.getString("pluginType");
		MetaDataSource metaDs = null;

		//0 否
		boolean isRelyPre = conf.getInt("isRelyPre", 0) != 0; 
		
		switch (PluginType.valueOf(stepInst)) {

		case ftpreader:
			// TODO 映射入参构建FTP DS
			if (isRelyPre) {
				metaDs = buildFtpDataSource(conf);
				break;
			}
		default:
			metaDs = getDbDataSource(conf);
		}

		return metaDs;
	}

	public MetaDataSource buildFtpDataSource(Configuration conf) {
		MetaDataSource ftpDs = new MetaDataSource();
		// VFS FTP 参数解析
		String vfs = Constant.GLOBAL_CONF.getString(Constant.DATAX_ENTRY_PARAM_FTP_VFS);
		// sftp://ftpusername:ftppassword@192.168.0.1:21/dir/dir1/
		if (Strings.isNullOrEmpty(vfs)) {
			LOG.warn("获取VFS URI参数失败 isnull.");
			//throw WorkerException.asDataXException(CommonErrorCode.RUNTIME_ERROR, "获取VFS URI参数失败 .");
			if(conf.getString("dataSourceId")!= null){
				return getDbDataSource(conf);
			}
		}
		VFSRelInfo extractToPath = null;
		try {
			extractToPath = VFSUriParser.extractToPath(vfs);
		} catch (FileSystemException e) {
			throw WorkerException.asDataXException(CommonErrorCode.RUNTIME_ERROR, "解析VFS URI失败 .", e);
		}
		LOG.info("\nVFS URI: {}", JSON.toJSONString(extractToPath, SerializerFeature.PrettyFormat));
		ftpDs.setDsAcct(extractToPath.getUserName());
		ftpDs.setDsAuth(extractToPath.getPassword());
		ftpDs.setDsConf(JSON.toJSONString(extractToPath));
		return ftpDs;
	}

	public MetaDataSource getDbDataSource(Configuration conf) {
		MetaDataSource dbDs = null;
		String dsId = conf.getNecessaryValue("dataSourceId", CommonErrorCode.CONFIG_ERROR);
		try {
			dbDs = dsRepository.findOne(dsId);
			LOG.info("\nMetaDataSource : {}" , JSON.toJSONString(dbDs, SerializerFeature.PrettyFormat));
			//加密
			String password = dbDs.getDsAuth();
			if(!Strings.isNullOrEmpty(password)){
				try{
					dbDs.setDsAuth(AesCipher.decrypt(password, Crypto.DEFAULT_SECRET_KEY));
				}catch(Exception e){
					LOG.warn(String.format("DB数据源 [%s]，解密失败 .", dsId));
				}
			}
		} catch (Exception e) {
			throw WorkerException.asDataXException(CommonErrorCode.RUNTIME_ERROR,
					String.format("未获取到DB数据源 [%s]，检查表 dacp_meta_datasource .", dsId), e);
		}
		return dbDs;
	}
	
	public static void main(String[] args) {
 		System.out.println(AesCipher.decrypt("CSv2g/bINGuLvXUu3fm7Ow==",Crypto.DEFAULT_SECRET_KEY));
	}
}
